/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package person.message;

import java.io.Serializable;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author gilberto
 */
@ManagedBean(name = "person_message")
@RequestScoped
public class Main extends Beans implements Serializable {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find person_messageFind = new Find();
    private List<Beans> person_messageList = new ArrayList<>();
    //Variables locales
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    private void load() {
        try {
            //Verifica si hay un registro seleccionado
            if (logged.getMasterId() == 0) {
                return;
            }

            map.clear();
            map.put("sm.id = " + logged.getDetailId(), " ");

            person_messageList.clear();
            person_messageList = person_messageFind.byMap(map);

            setId_receptor(person_messageList.get(0).getId_receptor());
            setId_mensaje(person_messageList.get(0).getId_mensaje());
            setEstatus(person_messageList.get(0).getEstatus());
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            setId_mensaje(logged.getTempId());
            Iterator iter = logged.getList_receptor().iterator();
            while (iter.hasNext()) {
                setId_receptor(Integer.parseInt(iter.next().toString()));
                sql = "INSERT INTO public.persona_mensaje (id_receptor, id_mensaje, estatus) "
                        + "VALUES ("
                        + getId_receptor() + ", "
                        + "'" + getId_mensaje() + "', "
                        + "'" + getEstatus() + "')";

                //Inserta la información del usuario
                persistencia.executeUpdate(sql);

            }
            clearBeans();

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }


        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {

        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.sistema_notificacion "
                + "WHERE id = " + id;

        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.setMasterId(0);
        clearBeans();
        map.clear();
    }

    public void selectedRecordId(int recordId) {
        logged.setMasterId(recordId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
